<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm
          :fieldList="fieldList"
          :formOption="optionsDataAll"
          :formData="form"
        >
          <template #create_user="{ value, input }">
            <VCascader
              :model-value="value"
              @update:model-value="input"
              collapse-tags
              class="w-[200px]"
              placeholder="请选择"
            />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <VActionBar :actions="actions" />
      </template>
      <template #operation="{ row }">
        <template v-if="row.parentId">
          <el-button
            link
            type="primary"
            @click="handleEdit(row.id, 2)"
            v-hasPermi="[logisticsSettingsAuthList.transit_timing.edit]"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(row.id)"
            v-hasPermi="[logisticsSettingsAuthList.transit_timing.delete]"
          >
            删除
          </el-button>
        </template>
        <template v-else>
          <el-button
            link
            type="primary"
            @click="handleEdit(row.id, 1)"
            v-hasPermi="[logisticsSettingsAuthList.transit_timing.edit]"
          >
            编辑
          </el-button>
        </template>
        <el-button link type="primary" @click="handleLog(row)">
          日志
        </el-button>
      </template>
    </VTable>
    <Add
      v-model="addVisible"
      :id="addId"
      :type="addType"
      :title="addTitle"
      :option="optionsDataAll"
      @close="addId = null"
      @refresh="refresh"
    />
    <SpecialLog
      dialog
      v-model="logVisible"
      :autoLoad="false"
      tag="TC_PRE_TIME_CONFIG"
      :business_id="logId"
      @close="logId = ''"
    />
    <ImportDialog ref="importDialogRef" @refresh="refresh" />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { preTimeConfigList, optWp, preTimeConfigDelete } from "./api.js";
import { renderCustomSlot } from "@/hooks/renderTable.jsx";
import XForm from "@/components/XForm/index.vue";
import { useEnumSelect } from "@/hooks/useEnumSelect.js";
import { getChannelList } from "@/api/index.js";
import { tipMessage } from "@/hooks/tool.js";
import SpecialLog from "@/components/SpecialLog/index.vue";
import Add from "./add/index";
import ImportDialog from "@/components/importDialog/index.vue";
import { logisticsSettingsAuthList } from "@/Auth/logistics-settings.js";
import { getCountry } from "@/api/index.js";
const { proxy } = getCurrentInstance();
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {},
  },
  treeConfig: {
    transform: true,
    rowField: "id",
    parentField: "parentId",
  },
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    {
      field: "transport_type_text",
      title: "运输类型",
      width: 120,
      treeNode: true,
    },
    { field: "wp_type_text", title: "类型", width: 80 },
    {
      field: "wp_names_ls",
      title: "仓点",
      width: 250,
      slots: renderCustomSlot("wp_names_ls"),
    },
    { field: "country_name", title: "国家", width: 100 },
    { field: "channel_name", title: "渠道", width: 300 },
    {
      field: "days_shipmentid_validity",
      title: "Shipmentid有效期",
      width: 150,
    },
    {
      field: "days_to_departure",
      title: "发货-开船",
      width: 130,
      slots: {
        header: () => (
          <div>
            <div>发货-开船(平均)</div>
            <div>发货-开船(标准)</div>
          </div>
        ),
        default: ({ row }) => {
          return (
            <div>
              <div>{row?.days_to_departure || 0}</div>
              <div>{row?.days_to_departure_standard || 0}</div>
            </div>
          );
        },
      },
    },
    {
      field: "days_to_arrival",
      title: "开船-到港",
      width: 130,
      slots: {
        header: () => (
          <div>
            <div>开船-到港(平均)</div>
            <div>开船-到港(标准)</div>
          </div>
        ),
        default: ({ row }) => {
          return (
            <div>
              <div>{row?.days_to_arrival || 0}</div>
              <div>{row?.days_to_arrival_standard || 0}</div>
            </div>
          );
        },
      },
    },
    {
      field: "days_to_customs_clearance",
      title: "到港-清关",
      width: 130,
      slots: {
        header: () => (
          <div>
            <div>到港-清关(平均)</div>
            <div>到港-清关(标准)</div>
          </div>
        ),
        default: ({ row }) => {
          return (
            <div>
              <div>{row?.days_to_customs_clearance || 0}</div>
              <div>{row?.days_to_customs_clearance_standard || 0}</div>
            </div>
          );
        },
      },
    },
    {
      field: "days_to_pickup",
      title: "清关-提取",
      width: 130,
      slots: {
        header: () => (
          <div>
            <div>清关-提取(平均)</div>
            <div>清关-提取(标准)</div>
          </div>
        ),
        default: ({ row }) => {
          return (
            <div>
              <div>{row?.days_to_pickup || 0}</div>
              <div>{row?.days_to_pickup_standard || 0}</div>
            </div>
          );
        },
      },
    },
    {
      field: "days_to_receipt",
      title: "提取-签收",
      width: 130,
      slots: {
        header: () => (
          <div>
            <div>提取-签收(平均)</div>
            <div>提取-签收(标准)</div>
          </div>
        ),
        default: ({ row }) => {
          return (
            <div>
              <div>{row?.days_to_receipt || 0}</div>
              <div>{row?.days_to_receipt_standard || 0}</div>
            </div>
          );
        },
      },
    },
    {
      field: "days_to_first_shelving",
      title: "签收-上架（第一次）",
      width: 230,
      slots: {
        header: () => (
          <div>
            <div>签收-上架（第一次）(平均)</div>
            <div>签收-上架（第一次）(标准)</div>
          </div>
        ),
        default: ({ row }) => {
          return (
            <div>
              <div>{row?.days_to_first_shelving || 0}</div>
              <div>{row?.days_to_first_shelving_standard || 0}</div>
            </div>
          );
        },
      },
    },
    {
      field: "days_to_full_shelving",
      title: "上架-完成（全部上架）",
      width: 230,
      slots: {
        header: () => (
          <div>
            <div>上架-完成（全部上架）(平均)</div>
            <div>上架-完成（全部上架）(标准)</div>
          </div>
        ),
        default: ({ row }) => {
          return (
            <div>
              <div>{row?.days_to_full_shelving || 0}</div>
              <div>{row?.days_to_full_shelving_standard || 0}</div>
            </div>
          );
        },
      },
    },
    {
      field: "todo",
      title: "异常时效差异",
      width: 420,
      slots: {
        default: ({ row }) => {
          return (
            <div class="grid grid-cols-2">
              <VText
                title="签收差异提醒天数(平均)"
                value={row?.days_receipt_variance_alert}
              />
              <VText
                title="上架差异提醒天数(平均)"
                value={row?.days_shelving_variance_alert}
              />
               <VText
                title="签收差异提醒天数(标准)"
                value={row?.days_receipt_variance_alert_standard}
              />
              <VText
                title="上架差异提醒天数(标准)"
                value={row?.days_shelving_variance_alert_standard}
              />
            </div>
          );
        },
      },
    },
    {
      field: "date",
      title: "人员时间信息",
      width: 420,
      slots: {
        default: ({ row }) => {
          return (
            <div class="grid grid-cols-2 gap-0">
              <VText title="更新人" value={row?.update_user} />
              <VText title="更新时间" value={row?.update_time} />
              <VText title="创建人" value={row?.create_user} />
              <VText title="创建时间" value={row?.create_time} />
            </div>
          );
        },
      },
    },
    {
      fixed: "right",
      title: "操作",
      width: 180,
      slots: {
        default: "operation",
      },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        return handleReq({ ...form, ...page });
      },
    },
  },
});

const handleReq = async (form) => {
  const { data, total } = await preTimeConfigList(form);
  let list = transformData(data);
  return {
    data: list,
    total,
  };
};
const transformData = (data, parentId = null) => {
  let result = [];
  data.forEach((item) => {
    result.push({ parentId, ...item });
    if (item.subs && item.subs.length > 0) {
      result = result.concat(transformData(item.subs, item.id));
    }
  });
  return result;
};
const { options: optionsData } = useEnumSelect({
  params: ["wp_type", "transport_type", "tc_time_config_type"],
});
watchEffect(async () => {
  const wpTypes = optionsData.value.wp_type;
  if (wpTypes && wpTypes.length) {
    let xy_data = [];
    for (let i = 0; i < wpTypes.length; i++) {
      const { data } = await optWp({ wp_type: wpTypes[i].value });
      optionsData.value["wp_type"][i].wp = data || [];
      xy_data.push(...(data || []));
    }
    optionsData.value.xyChannel = xy_data;
  }
});
// 初始化数据函数
const optionsData1 = ref({});
const getChannel = async () => {
  const { data } = await getChannelList();
  optionsData1.value.channel = data || [];
};
getChannel();
const getCountryList = async () => {
  const { data } = await getCountry();
  optionsData1.value.country = data;
};
getCountryList();
const optionsDataAll = computed(() =>
  Object.assign({}, optionsData.value, optionsData1.value)
);
const addVisible = ref(false);
const addId = ref(null);
const addTitle = ref("新增");
const addType = ref(1);
const handleEdit = (val, type) => {
  addId.value = val;
  addType.value = type;
  addTitle.value = type == 1 ? "编辑" : "渠道编辑";
  addVisible.value = true;
};
const handleDelete = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除选中的
        <span class="text-[#3366F1] px-[4px]">1</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message, data } = await preTimeConfigDelete({ id });
          if (code != 200) {
            ElMessage.error(message);
            return;
          }
          tipMessage(data);
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const logId = ref("");
const logVisible = ref(false);
const handleLog = (item) => {
  logId.value = item.id;
  logVisible.value = true;
};
//导入
const importDialogRef = ref();
const handleImport = () => {
  importDialogRef.value?.open({
    type: "sys.importTcPreTimeConfig",
    urlType: "/sys/tc-pre-time-config/import",
  });
};
const handleExport = () => {};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "transport_type",
    type: "select",
    multiple: true,
    originOption: "transport_type",
    style: { width: "200px" },
    class: "select-wrapper-style",
    options: {
      placeholder: "运输类型",
    },
  },
  {
    field: "xy_ls_channel_id",
    type: "select",
    multiple: true,
    originOption: "xyChannel",
    style: { width: "240px" },
    class: "select-wrapper-style",
    options: {
      placeholder: "仓点",
      labelKey: "wp_name",
      valueKey: "wp_id",
    },
  },
  {
    field: "channel_ids",
    type: "select",
    multiple: true,
    originOption: "channel",
    style: { width: "240px" },
    class: "select-wrapper-style",
    options: {
      placeholder: "物流渠道",
      labelKey: "channel_name",
      valueKey: "channel_id",
    },
  },
  {
    field: "time",
    type: "dateTimeRange",
    style: { width: "360px" },
    selectStyle: { width: "100px" },
    select: [
      { label: "创建时间", value: "create_time" },
      { label: "更新时间", value: "update_time" },
    ],
    itemProps: {
      startPlaceholder: "最早时间",
      endPlaceholder: "最晚时间",
    },
  },
  {
    field: "user",
    selectStyle: { width: "100px" },
    select: [
      { label: "创建人", value: "create_user" },
      { label: "更新人", value: "update_user" },
    ],
    options: {
      placeholder: "请选择",
    },
    slot: "create_user",
  },
];
const actions = [
  {
    label: "新增",
    type: "primary",
    icon: "add2",
    fn: () => (
      (addVisible.value = true), (addTitle.value = "新增"), (addType.value = 1)
    ),
    permission: [logisticsSettingsAuthList.transit_timing.add],
  },
  {
    label: "导入",
    right: true,
    dkicon: "icon-Download",
    fn: handleImport,
    permission: [logisticsSettingsAuthList.transit_timing.import],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [logisticsSettingsAuthList.transit_timing.export],
  },
];
</script>
<style lang="scss" scoped></style>
